package com.easy.cart.controller;

import com.easy.bean.Carts;
import com.easy.bean.Users;
import com.easy.cart.service.ICartService;
import com.easy.cart.service.feign.EasyFeignService;
import com.easy.common.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("cart")
public class CartController {
    @Autowired
    ICartService cartS;
    @Autowired
    EasyFeignService feignS;

    /**
     * 加入购物车:
     * 所需要的数据(前台准备  商品id  数量    token(随着请求一起携带))
     * 后台接收到请求(VUE项目访问后台----8888gateway)
     * 1.将token传递给User模块查询认证用户的信息
     * 2.将[商品id,数量,用户id]封装成一个Cart对象
     * 3.检查购物车中是否有该对象[商品id,用户id]
     * 有:在该用户的该商品的数量上累加[数量]即可
     * 无:在购物车表中新增一条数据[商品id,数量,用户id]
     *
     * @param cart
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, path = "/")
    public CommonResult addCart(Carts cart, HttpServletRequest request) {
        //获取请求中的token
        String token = request.getHeader("Authorization");
        //通过用户模块使用token获取认证用户信息 CommonResult.data ---次对象中不能出现密码
        Users user = feignS.loginUser(token);
        //判断获取的对象是Users对象  ---保证类型安全
        if (user == null) {
            System.out.println("instanceof  false");
            return CommonResult.failed(401, "未认证");
        }
        cart.setUserid(user.getId());
        cartS.addCarts(cart);
        return CommonResult.success();
    }

    @RequestMapping(method = RequestMethod.GET, path = "/")
    public CommonResult getCartList(HttpServletRequest request) {
        //获取请求中的token
        String token = request.getHeader("Authorization");
        //通过用户模块使用token获取认证用户信息 CommonResult.data ---次对象中不能出现密码
        Users user = feignS.loginUser(token);
        List<Carts> list=cartS.getCartsList(user.getId());
        return CommonResult.success(list);
    }

    @RequestMapping(method = RequestMethod.PUT, path = "/")
    public CommonResult editCartCount(int id,int quantity){
        cartS.editCartsCount(id,quantity);
        return CommonResult.success();
    }

    @RequestMapping(method = RequestMethod.PUT, path = "/select")
    public CommonResult editCartSelected(int id,int selected){
        cartS.editCartsSelect( id, selected);
        return CommonResult.success();
    }
    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public CommonResult deleteCart(@PathVariable int id){
        cartS.deleteCarts(id);
        return CommonResult.success();
    }

}
